package com.after.saas.common.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname ListUtil
 * @Description TODO
 * @Date 2021/4/24 11:08
 * @Created by hjchen
 */
public class ListUtil {


    public static <E, T> List<T> copyList(List<E> sources, Class<T> c) {
        List<T> list = new ArrayList<>();
        if (ObjectUtil.isEmpty(sources)) {
            return list;
        }
        for (E source : sources) {
            list.add(copy(source, c));
        }
        return list;
    }

    public static <T> T copy(Object source, Class<T> c) {
        if (source == null) {
            return null;
        }
        try {
            T instance = c.newInstance();
            BeanUtil.copyProperties(source, instance);
            return instance;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T[] toArray(List<T> source) {
        if (ObjectUtil.isNotEmpty(source)) {
            Class clazz = source.get(0).getClass();
            T[] a = (T[]) Array.newInstance(clazz, source.size());
            return source.toArray(a);
        }
        return null;
    }

}
